package com.chat.api.listener;

import com.chat.api.utils.util.MapUtilss;
import org.assertj.core.util.Maps;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class RequestListen implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent event) {

    }

    @Override
    public void requestInitialized(ServletRequestEvent event) {
        HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
        Map<String,String> map = (Map<String, String>) event.getServletContext().getAttribute("sessionMap");
        if (map == null){
            Map<String, String> map1 = new HashMap<>();
            event.getServletContext().setAttribute("sessionMap",map1);
        }
        Map<String,String> sessionMap = (Map<String, String>) event.getServletContext().getAttribute("sessionMap");
        String id = request.getSession().getId();
        Boolean result = MapUtilss.findMapKey(sessionMap, id);
        if (!result){
//            System.out.println("***********当前用户不存在于服务器,向服务器添加该用户");
            sessionMap.put(id,request.getRemotePort()+"");
            event.getServletContext().setAttribute("sessionMap",sessionMap);
        }
//        System.out.println("当前在线人数： " +event.getServletContext().getAttribute("userCount"));
    }
}
